package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类，提供发送GET和POST请求的方法
 */
public class HttpClientUtil {

    // 设置连接超时时间常量，单位为毫秒
    static final int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     *
     * @param url      请求的URL地址
     * @param paramMap 请求的参数键值对
     * @return 请求结果字符串
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象，用于发送HTTP请求
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = ""; // 初始化结果字符串
        CloseableHttpResponse response = null; // 初始化响应对象

        try {
            URIBuilder builder = new URIBuilder(url); // 使用URIBuilder构建URL
            if (paramMap != null) {
                // 遍历参数Map，添加到URL中
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build(); // 构建最终的URI

            // 创建GET请求对象
            HttpGet httpGet = new HttpGet(uri);

            // 发送请求并获取响应
            response = httpClient.execute(httpGet);

            // 判断响应状态码是否为200，如果是则读取响应内容
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
        } finally {
            try {
                // 关闭响应和httpClient资源
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace(); // 打印异常堆栈信息
            }
        }

        return result; // 返回请求结果
    }

    /**
     * 发送POST方式请求，参数以表单形式提交
     *
     * @param url      请求的URL地址
     * @param paramMap 请求的参数键值对
     * @return 请求结果字符串
     * @throws IOException 可能抛出的IO异常
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象，用于发送HTTP请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null; // 初始化响应对象
        String resultString = ""; // 初始化结果字符串

        try {
            // 创建HttpPost请求对象
            HttpPost httpPost = new HttpPost(url);

            // 创建NameValuePair列表，用于存放请求参数
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 构建表单实体
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity); // 设置请求实体
            }

            httpPost.setConfig(builderRequestConfig()); // 设置请求配置

            // 执行HTTP请求并获取响应
            response = httpClient.execute(httpPost);

            // 读取响应内容并转换为字符串
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e; // 抛出异常
        } finally {
            try {
                // 关闭响应资源
                response.close();
            } catch (IOException e) {
                e.printStackTrace(); // 打印异常堆栈信息
            }
        }

        return resultString; // 返回请求结果
    }

    /**
     * 发送POST方式请求，参数以JSON格式提交
     *
     * @param url      请求的URL地址
     * @param paramMap 请求的参数键值对
     * @return 请求结果字符串
     * @throws IOException 可能抛出的IO异常
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象，用于发送HTTP请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null; // 初始化响应对象
        String resultString = ""; // 初始化结果字符串

        try {
            // 创建HttpPost请求对象
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                // 构建JSON对象，存放请求参数
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                // 创建StringEntity实体，设置内容类型为application/json
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                // 设置请求头内容编码
                entity.setContentEncoding("utf-8");
                // 设置请求头内容类型为application/json
                entity.setContentType("application/json");
                httpPost.setEntity(entity); // 设置请求实体
            }

            httpPost.setConfig(builderRequestConfig()); // 设置请求配置

            // 执行HTTP请求并获取响应
            response = httpClient.execute(httpPost);

            // 读取响应内容并转换为字符串
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e; // 抛出异常
        } finally {
            try {
                // 关闭响应资源
                response.close();
            } catch (IOException e) {
                e.printStackTrace(); // 打印异常堆栈信息
            }
        }

        return resultString; // 返回请求结果
    }

    /**
     * 构建请求配置，设置连接超时、请求超时和套接字超时时间
     *
     * @return 返回构建好的RequestConfig对象
     */
    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC) // 设置连接超时时间
                .setConnectionRequestTimeout(TIMEOUT_MSEC) // 设置请求超时时间
                .setSocketTimeout(TIMEOUT_MSEC) // 设置套接字超时时间
                .build(); // 构建RequestConfig对象
    }

}
